function gpGalleryField( $ ) {

	$( '.gp-settings-section.gp-show .gp-gallery-field' ).each( function() {
		 		
		var	field = $( this ),
			uploadButton = field.find( '.gp-media-button' ),
			removeButton = field.find( '.gp-remove-media-button' ),
			addText = uploadButton.data( 'add' ),
			changeText = uploadButton.data( 'change' ),
			attachmentIDsField = field.find( '.gp-attachment-ids' ),
			galleryUploader;
		
		uploadButton.click( function( e ) {

			e.preventDefault();

			if ( galleryUploader ) {
				galleryUploader.open();
				return;
			}

			// Generate media window
			galleryUploader = wp.media.frames.file_frame = wp.media({
				title: uploadButton.val(),
				button: {
					text: uploadButton.val()
				},
				multiple: true 
			});
			
			// When opening media window
			galleryUploader.on( 'open', function() {
			
				 var selection = galleryUploader.state().get( 'selection' ),
				 	selectedIDs = attachmentIDsField.val(),
					selectedIDsArr = selectedIDs.split( ',' ).map( function( selectedIDs ) { 
						return Number( selectedIDs );
					});

				// When opening media window mark currently selected media 
				$.each( selectedIDsArr, function( key, value ) {
					selection.add( [ wp.media.attachment( value ) ] );
				});
	
			});
	
			// When selecting media in media window
			galleryUploader.on( 'select', function() {
			
				var attachments = galleryUploader.state().get( 'selection' ).map( 
					function( attachments ) {
						attachments.toJSON();
						return attachments;
					});
					
				var attachment_ids = [],
					i;
					
				uploadButton.val( changeText );				
				removeButton.addClass( 'gp-show' );
				
				// Remove all images from preview
				field.find( '.gp-gallery-preview' ).empty();
				
				for ( i = 0; i < attachments.length; i++ ) {
					attachment_ids[i] = attachments[i].id;
					if ( attachment_ids[i] > 0 ) {
						field.find( '.gp-gallery-preview' ).append( '<img src="' + attachments[i].attributes.sizes.thumbnail.url +'">' );
					}	
				}
				
				// Update hidden field with attachments IDs
				if ( attachment_ids ) {
					attachmentIDsField.val( attachment_ids.join( ',' ) );
				}
				
			});
			
			galleryUploader.open();
			
		});
				
		// Clicking remove button		
		removeButton.click( function( e ) {
			e.preventDefault();
			var attachment_ids = [];
			attachmentIDsField.val( '' );
			field.find( '.gp-gallery-preview img' ).remove();
			$( this ).removeClass( 'gp-show' );
			uploadButton.val( addText );
		});
	
	});
				
}


jQuery( function( $ ) {

	'use strict';

	gpGalleryField( $ );
			
});